package netty.heartbeat;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.handler.timeout.IdleState;
import io.netty.handler.timeout.IdleStateEvent;

/**
 * @author: 程序员七哥
 * @date: 2021-12-13
 * @description:
 */
public class ReadDataHandler extends ChannelInboundHandlerAdapter {

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        System.out.println("接受到客户端发送的数据：" + ctx.channel().remoteAddress() + ": " + msg);
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        System.out.println("出现异常了！");
        ctx.close();
    }

    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
        // 空闲超时事件
        if (evt instanceof IdleStateEvent) {
            final IdleState idleState = ((IdleStateEvent) evt).state();
            // 服务端超时没有收到客户端发送的消息
            if (IdleState.READER_IDLE == idleState) {
                System.out.println("长时间未收到客户端的消息，断开连接：" + ctx.channel().remoteAddress());
                // 断开连接
                ctx.disconnect();
            }
        }
    }
}
